package com.yeziji.devops.sql.constructor;

import cn.hutool.core.util.StrUtil;
import com.yeziji.devops.common.expcetion.SqlBuilderException;
import com.yeziji.devops.common.msg.SqlBuilderErrorMsg;
import com.yeziji.devops.constant.SqlExecuteTypeEnum;
import com.yeziji.devops.sql.SqlBuilderFactory;
import com.yeziji.devops.sql.base.SqlConstructorBase;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;

/**
 * 更新 SQL 构造器
 *
 * @author gzkemays
 * @since 2023/01/07 1:36 PM
 */
@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class UpdateSqlConstructor extends SqlConstructorBase {
    /**
     * 键值对更新数据
     */
    @NotEmpty(message = "必须传入键值对用于更新")
    private Map<String, Object> data;

    /**
     * 自动生成日期
     * <p>
     * 输入需要生成日期的字段名称
     * </p>
     */
    String genDate;

    @Override
    protected void check() {
        super.setType(SqlExecuteTypeEnum.UPDATE.getValue());
        super.check();

        if (this.data.isEmpty()) {
            throw new SqlBuilderException(SqlBuilderErrorMsg.DATA_EMPTY);
        }
        if (StrUtil.isBlank(super.wrapper)) {
            throw new SqlBuilderException(SqlBuilderErrorMsg.WRAPPER_IS_EMPTY);
        } else if (super.wrapper.trim().equals("1=1")) {
            throw new SqlBuilderException(SqlBuilderErrorMsg.WRAPPER_IS_ILLEGAL);
        }
    }

    @Override
    public String buildSql() {
        if (StrUtil.isNotBlank(this.sql)) {
            return sql;
        }

        this.check();
        return new SqlBuilderFactory().getSqlBuilder(SqlExecuteTypeEnum.UPDATE, this).execute();
    }

    public static void main(String[] args) {
        Map<String, Object> data = new HashMap<>();
        data.put("a", 1);
        UpdateSqlConstructor constructor =
                UpdateSqlConstructor.builder()
                        .type("update")
                        .table("yzj_forum")
                        .data(data)
                        .wrapper("enabled=true")
                        .build();
        System.out.println("constructor = " + constructor.buildSql());
    }
}
